package com.css.ids.server.service.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.css.apps.base.func.model.SFunc;
import com.css.apps.base.func.model.SFuncAction;
import com.css.apps.base.role.model.SRole;
import com.css.db.query.JoinList;
import com.css.db.query.QueryCache;
import com.css.util.StringHelper;

public class IdsFuncDao {

	public static SFunc getFunc(String uuid) {
        return QueryCache.get(SFunc.class, uuid);
    }
	
	@SuppressWarnings("unchecked")
	public static List<SFunc> listFuncs(Collection<String> funcIds) {
		return QueryCache.idToObj(SFunc.class, new ArrayList<>(funcIds));
	}
	
	public static List<SFunc> getFuncByUserId(String userId) {
    	return getFuncByUserId(userId, null);
    }
	
	@SuppressWarnings("unchecked")
	public static List<SFunc> getFuncByUserId(String userId, String sysId) {
        List<SFunc> funcs = new ArrayList<SFunc>();
        List<SRole> roles = null;
        if(StringHelper.isEmpty(sysId)) {
        	roles = IdsRoleDao.getRoleByUserId(userId);
        } else {
        	roles = IdsRoleDao.getRoleByUserId(userId, sysId);
        }
        if (roles != null && roles.size() > 0) {
            for (SRole role : roles) {
            	JoinList jl = role.getRoleFuncList();
            	if (jl != null) {
            		List<SFunc> list = jl.getList();
            		if (list != null && list.size() > 0) {
            			funcs.addAll(list);
            		}
            	}
            }
        }
        return funcs;
    }

	@SuppressWarnings("unchecked")
	public static List<SFuncAction> getFuncActionByUserId(String userId, String sysId) {
        List<SFuncAction> funcActions = new ArrayList<SFuncAction>();
        List<SFunc> funcs = getFuncByUserId(userId, sysId);
        if (funcs != null && funcs.size() > 0) {
            for (SFunc func : funcs) {
                List<SFuncAction> list = func.getFuncActionList().getList();
                if (list != null && list.size() > 0) {
                    funcActions.addAll(list);
                }
            }
        }
        return funcActions;
    }
	
    @SuppressWarnings("unchecked")
    public static List<SFunc> listFuncsByRoleId(String roleId) {
        return new QueryCache("from SFunc a where a.uuid in (select b.funcId from SRoleFunc b where b.roleId = :roleId)")
        		.setParameter("roleId", roleId).list();
    }
	
}
